<?php
class Authenticatecontroller{

	/**
	 * Registry object reference
	 */
	private $registry;

	/**
	 * Quotation model object reference
	 */
	private $model;

	/**
	 * Controller constructor - direct call to false when being embedded via another controller
	 * @param Registry $registry our registry
	 * @param bool $directCall - are we calling it directly via the framework (true), or via another controller (false)
	 */
	public function __construct( Registry $registry, $directCall )
	{
		$this->registry = $registry;

		$urlBits = $this->registry->getObject('url')->getURLBits();
		if( isset( $urlBits[1] ) )
		{
			switch( $urlBits[1] )
			{
				case 'logout':
					$this->logout();
					break;
				case 'login':
					$this->login();
					break;
				case 'username':
					$this->forgotUsername();
					break;
				case 'password':
					{
						$this->forgotPassword();					
					}
					break;
				case 'reset-password':
					$this->resetPassword( intval($urlBits[2]), 
							$this->registry->getObject('db')->sanitizeData($urlBits[3]) );
					break;
				case 'register':
					$this->registrationDelegator();
					break;
				case 'check':
					{
						$this->validateRegistration();
						//echo 'NO';
							
					}
					break;
			}

		}

	}

	private function forgotUsername()
	{
		if( isset( $_POST['email'] ) && $_POST['email'] != '' )
		{
			$e = $this->registry->getObject('db')->sanitizeData( $_POST['email'] );
			$sql = "SELECT * FROM users WHERE email='{$e}'";
			$this->registry->getObject('db')->executeQuery( $sql );
			if( $this->registry->getObject('db')->numRows() == 1 )
			{
				$data = $this->registry->getObject('db')->getRows();
				// email the user
				$this->registry->getObject('mailout')->startFresh();
				$this->registry->getObject('mailout')->setTo( $_POST['email'] );
				$this->registry->getObject('mailout')->setSender( $this->registry->getSetting('adminEmailAddress') );
				$this->registry->getObject('mailout')->setFromName( $this->registry->getSetting('cms_name') );
				$this->registry->getObject('mailout')->setSubject( 'Username details for ' .$this->registry->getSetting('sitename') );
				$this->registry->getObject('mailout')->buildFromTemplates('authenticate/username.tpl.php');
				$tags = $this->values;
				$tags[ 'sitename' ] = $this->registry->getSetting('sitename');
				$tags['username'] = $data['username'];
				$tags['siteurl'] = $this->registry->getSetting('siteurl');
				$this->registry->getObject('mailout')->replaceTags( $tags );
				$this->registry->getObject('mailout')->setMethod('sendmail');
				$this->registry->getObject('mailout')->send();

				// tell them that we emailed them
				$this->registry->errorPage('Username reminder sent', 'We have sent you a reminder of your username, to the email address we have on file');

			}
			else
			{
				// no user found
				$this->registry->getObject('template')->buildFromTemplates( 'header.tpl.php', 'authenticate/username/main.tpl.php', 'footer.tpl.php');
				$this->registry->getObject('template')->addTemplateBit('error_message', 'authenticate/username/error.tpl.php');
			}
		}
		else
		{
			// form template
			$this->registry->getObject('template')->buildFromTemplates( 'header.tpl.php', 'authenticate/username/main.tpl.php', 'footer.tpl.php');
			$this->registry->getObject('template')->getPage()->addTag('error_message', '');
		}
	}

	private function generateKey( $len = 7 )
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		// 36 chars
		$tor = '';
		for( $i = 0; $i < $len; $i++ )
		{
			$tor .= $chars[ rand() % 35 ];
		}
		return $tor;
	}

	private function forgotPassword()
	{
		if( isset( $_POST['username'] ) && $_POST['username'] != '' )
		{
			$u = $this->registry->getObject('db')->sanitizeData( $_POST['username'] );
			$sql = "SELECT * FROM users WHERE username='{$u}'";
			$this->registry->getObject('db')->executeQuery( $sql );
			if( $this->registry->getObject('db')->numRows() == 1 )
			{
				$data = $this->registry->getObject('db')->getRows();
				// have they requested a new password recently?
				//if( $data['reset_expires'] > date('Y-m-d h:i:s') )
				//{
					// inform them
				//	$this->registry->errorPage('Error sending password request', 'You have recently requested a password reset link, and as such you must wait a short while before requesting one again.  This is for security reasons.');
			//	}
				//else
				{
					// update their row
					$changes = array();
					$rk = $this->generateKey();
					$changes['reset_key'] = $rk;

					$changes['reset_expires'] = date( 'Y-m-d H:i:s', time()+86400 );
					$this->registry->getObject('db')->updateRecords( 'users', $changes, 'uid=' . $data['uid'] );
					//
					
					$this->registry->getObject('mailout')->startFresh();
					$this->registry->getObject('mailout')->setTo($_POST['username']);
					$this->registry->getObject('mailout')->setSender('');
					$this->registry->getObject('mailout')->setSubject( 'Password reset request at ' .$this->registry->getSetting('sitename') );
					$this->registry->getObject('mailout')->buildFromTemplates('emailtemplates/passwordreset_eml.tpl');
					
					$tags['sitename'] = $this->registry->getSetting('sitename');
					$tags['username'] = $data['username'];
					$url = $this->registry->getObject('url')->buildURL( array('authenticate', 'reset-password', $data['uid'], $rk), '', false);
				
					$tags['url'] = $url;
					echo $url;
					$tags['siteurl'] = $this->registry->getSetting('siteurl');
					$this->registry->getObject('mailout')->replaceTags( $tags );
					$this->registry->getObject('mailout')->setMethod('sendmail');
					$this->registry->getObject('mailout')->appendHeader('MIME-Version: 1.0');
					$this->registry->getObject('mailout')->appendHeader('Content-Type: text/html; charset=ISO-8859-1');
					$this->registry->getObject('mailout')->send();

					// tell them that we emailed them
					
					$backurl = "We have sent you a link which will allow you to reset your account password.";
				
					$this->registry->errorPage('Password reset link sent', $backurl);
				}
			}
			else
			{	
				// no user found
				$this->registry->getObject('template')->buildFromTemplates('authenticate/forgotpwd/forgotpwd.tpl.php');
				$this->registry->getObject('template')->getPage()->addTag('error_message', 'Invalid User Name');
				$this->registry->getObject('template')->getPage()->addTag( 'referer', '');
			}
		}
		else
		{
			// form template
			$this->registry->getObject('template')->buildFromTemplates('authenticate/forgotpwd/forgotpwd.tpl.php');
			$this->registry->getObject('template')->getPage()->addTag('error_message', '');
			$this->registry->getObject('template')->getPage()->addTag( 'referer', '');
		}
	}

	private function resetPassword( $user, $key )
	{
		$this->registry->getObject('template')->getPage()->addTag( 'user', $user );
		$this->registry->getObject('template')->getPage()->addTag('key', $key );
		$sql = "SELECT * FROM users WHERE uid={$user} AND reset_key='{$key}'";
		$this->registry->getObject('db')->executeQuery( $sql );
		
		$errorNewPassword = '';
		$errorConfirmPassword = '';
		$errorCurrentPassword = '';
		
		
		if( $this->registry->getObject('db')->numRows() == 1 )
		{
			$data = $this->registry->getObject('db')->getRows();
			$currentPwdHash = $data['password_hash'];
					
			if( $data['reset_expires'] < date('Y-m-d H:i:s') )
			{
				$this->registry->errorPage('Reset link expired', 'Password reset links are only valid for 24 hours and only for one time.');

			}
			else
			{
				if (isset($_POST['newpwd']) && isset($_POST['confirmpwd']))
				{
					if( $_POST['newpwd'] != $_POST['confirmpwd'] )
					{
						$errorConfirmPassword = 'Password confirm mismatch';
					}
					else
					{
						if( strlen( $_POST['newpwd'] ) < 6 )
						{
							$errorNewPassword = 'Password too short';
						}
						else	// Success
						{
							$changes = array();
							$changes['password_hash'] = md5( $_POST['newpwd'] );
							$changes['reset_expires'] = date( 'Y-m-d H:i:s', time());
							$this->registry->getObject('db')->updateRecords( 'users', $changes, 'uid=' . $user );
							$this->registry->errorPage('Password reset',
									'Your password has been reset to the one you entered');								
							return;
						}
					}
				}
				
				$this->registry->getObject('template')->buildFromTemplates('authenticate/forgotpwd/passwordreset.php');
				$this->registry->getObject('template')->getPage()->addTag( 'crnt_error_message', $errorCurrentPassword);
				$this->registry->getObject('template')->getPage()->addTag( 'new_error_message', $errorNewPassword);
				$this->registry->getObject('template')->getPage()->addTag( 'confirm_error_message', $errorConfirmPassword);
				$this->registry->getObject('template')->getPage()->addTag( 'userid', $user);
				$this->registry->getObject('template')->getPage()->addTag( 'resetkey', $key);
			}
		}
		else
		{
			$this->registry->errorPage('Invalid details', 'The password reset link was invalid');
		}
	}

	private function login()
	{
		// template
		if( $this->registry->getObject('authenticate')->isJustProcessed() )
		{
			if( $this->registry->getObject('authenticate')->isLoggedIn() == false )
			{
				// invalid details
				$this->registry->getObject('template')->addTemplateBit('error_message', 'authenticate/login/error.tpl.php');
			}
			else
			{
				// Create page headers
				$this->CreatePageHeaders();

				echo $_POST['referer'];
				
				// bounce them away!
				if( $_POST['referer'] == '' )
				{
					$url = $this->registry->getObject('url')->buildURL( array('profile', 'home'), '', false );
					$this->registry->redirectUser( $url);
				}
				else
				{
					$this->registry->redirectUser( $_POST['referer']);
				}
			}
		}
		else
		{
			if( $this->registry->getObject('authenticate')->isLoggedIn() == true )
			{
				$this->registry->errorPage( 'Already logged in', 'You cannot login as you are already logged in as <strong>' . $this->registry->getObject('authenticate')->getUser()->getUsername() . '</strong>');
			}
			else
			{
				$this->registry->getObject('template')->buildFromTemplates( 'login.tpl.php', 'footer.tpl.php' );
				$this->registry->getObject('template')->getPage()->addTag( 'referer', $this->registry->getSetting('siteurl'));
				$this->registry->getObject('template')->addTemplateBit('error_message', 'authenticate/login/error.tpl.php');
			}
		}

	}

	private function logout()
	{
		$this->registry->getObject('authenticate')->logout();

		$this->registry->getObject('template')->buildFromTemplates('login.tpl.php');
		$url = $this->registry->getObject('url')->buildURL( array('profile'), '', false );
		$this->registry->getObject('template')->getPage()->addTag( 'referer', $url);
		$this->registry->getObject('template')->getPage()->addTag( 'error_message', "");
		$this->registry->getObject('template')->getPage()->addTag('sitename', $this->registry->getSetting('sitename'));
	}

	/**
	 * Delegate control to the registration controller
	 * @return void
	 */
	private function registrationDelegator()
	{
		require_once FRAMEWORK_PATH . 'controllers/authenticate/registrationcontroller.php';
		$rc = new Registrationcontroller( $this->registry );

	}

	private function validateRegistration()
	{
		$urlBits = $this->registry->getObject('url')->getURLBits();
		if (!isset($_POST['register_email']))
		return 'INVALID';
			
		$user = $_POST['register_email'];
		$value = 'OK';

		switch( $urlBits[2] )
		{
			case 'email':
				{
					$sql = "SELECT * FROM users WHERE username='{$user}' AND deleted=0";

					//echo $sql;
					$this->registry->getObject('db')->executeQuery( $sql );
					if( $this->registry->getObject('db')->numRows() == 1 )
					{
						echo  "INVALID";
					}
				}
				break;
			default:
				break;
		}

		echo $value;
	}

	private function CreatePageHeaders()
	{
		$this->registry->getObject('template')->buildFromTemplates('main/main.tpl.php', 'main/main_menu.tpl.php','main/main_content.tpl.php' ,'main/footer.tpl.php');
		
		$cache = $this->registry->getObject('db')->cacheData(  $this->registry->getObject('authenticate')->getUser()->getProfiles() );
		$this->registry->getObject('template')->getPage()->addTag( 'profiles', array( 'DATA', $cache) );
		$this->registry->getObject('template')->getPage()->addTag('sitename', $this->registry->getSetting('sitename'));

		$this->registry->getObject('template')->getPage()->addTag( 'username', $this->registry->getObject('authenticate')->getUser()->getCurrentProfile()->getName());
		$this->registry->getObject('template')->getPage()->addTag( 'profile_id', $this->registry->getObject('authenticate')->getUser()->getCurrentProfile()->getProfileID());
	}


}


?>